package com.xishu.service;

import com.xishu.bo.Stock;
import com.xishu.entity.order.Order;
import com.xishu.entity.order.OrderItem;
import com.xishu.entity.shop.Item;
import com.xishu.entity.shop.OrderItemLockNumber;
import com.xishu.util.ClassUtil;
import com.xishu.util.Tools;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

@Component
public class UpdateOrderItemCountService implements Tools {
    @Transactional(rollbackFor = Exception.class)
    public List<Stock> updateOrderItemCount(Order orderInDb, OrderItem orderItem, int countAfterUpdate, Long orderItemId) throws Exception {
        //统一成先释放锁定量，再加上锁定量
        StockService stockService = StockService.getInstance();
        OrderItem cloneOrderItem = (OrderItem) ClassUtil.clone(orderItem);

        //释放锁定量
        OrderItemLockNumber orderItemLockNumber = stockService.filterOrderItemLockNumber(orderInDb, orderItemId);
        stockService.releaseLockNumber(orderItemLockNumber);

        //添加锁定量
        cloneOrderItem.setCount(countAfterUpdate);
        List<Stock> stockList = stockService.orderItemToStock(cloneOrderItem, false);
        List<Stock> stockListResult = stockService.stockManage(orderInDb.getShopId(), stockList);

        if (isNotEmpty(stockListResult)) {
            //没有锁成功，回退
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            //清空Item的缓存
            stockList.forEach(stock -> {
                Long itemId = stock.getItemId();
                Item item = new Item();
                item.setId(itemId);
                CommonService.getInstance().deleteFromCache(item);
            });
        }

        return stockListResult;
    }
}
